import React, { useState } from 'react';
import { Card, Form, Input, Select, Button, Table, Space, Tag, message } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';

interface UserType {
  key: string;
  name: string;
  age: number;
  email: string;
  status: 'active' | 'inactive';
  role: string;
  registerTime: string;
}

// 模拟用户数据
const generateFakeData = (count: number): UserType[] => {
  return Array.from({ length: count }, (_, index) => ({
    key: `${index + 1}`,
    name: `用户${index + 1}`,
    age: Math.floor(Math.random() * 40) + 18,
    email: `user${index + 1}@example.com`,
    status: Math.random() > 0.5 ? 'active' : 'inactive',
    role: ['管理员', '普通用户', 'VIP用户'][Math.floor(Math.random() * 3)],
    registerTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toLocaleDateString()
  }));
};

const UserManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<UserType[]>(() => generateFakeData(100));
  const [filteredData, setFilteredData] = useState<UserType[]>(data);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: data.length
  });

  const columns: TableProps<UserType>['columns'] = [
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      sorter: (a, b) => a.age - b.age,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      filters: [
        { text: '管理员', value: '管理员' },
        { text: '普通用户', value: '普通用户' },
        { text: 'VIP用户', value: 'VIP用户' },
      ],
      onFilter: (value, record) => record.role === value,
    },
    {
      title: '注册时间',
      dataIndex: 'registerTime',
      key: 'registerTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link">编辑</Button>
          <Button type="link" danger>删除</Button>
        </Space>
      ),
    },
  ];

  const handleSearch = async (values: any) => {
    setLoading(true);
    try {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500));

      const filtered = data.filter(item => {
        const matchName = !values.name || item.name.includes(values.name);
        const matchStatus = !values.status || item.status === values.status;
        const matchRole = !values.role || item.role === values.role;
        return matchName && matchStatus && matchRole;
      });

      setFilteredData(filtered);
      setPagination(prev => ({
        ...prev,
        current: 1,
        total: filtered.length
      }));
      message.success('查询成功');
    } catch (error) {
      message.error('查询失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.resetFields();
    setFilteredData(data);
    setPagination(prev => ({
      ...prev,
      current: 1,
      total: data.length
    }));
  };

  const handleTableChange: TableProps<UserType>['onChange'] = (newPagination, filters, sorter) => {
    setPagination(prev => ({
      ...prev,
      ...newPagination,
    }));
  };

  return (
    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
      <Card>
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: '20px' }}
        >
          <Form.Item name="name" label="用户名">
            <Input placeholder="请输入用户名" allowClear />
          </Form.Item>
          
          <Form.Item name="status" label="状态">
            <Select
              placeholder="请选择状态"
              allowClear
              style={{ width: 120 }}
              options={[
                { value: 'active', label: '启用' },
                { value: 'inactive', label: '禁用' },
              ]}
            />
          </Form.Item>
          
          <Form.Item name="role" label="角色">
            <Select
              placeholder="请选择角色"
              allowClear
              style={{ width: 120 }}
              options={[
                { value: '管理员', label: '管理员' },
                { value: '普通用户', label: '普通用户' },
                { value: 'VIP用户', label: 'VIP用户' },
              ]}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />} loading={loading}>
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table
          columns={columns}
          dataSource={filteredData}
          pagination={pagination}
          onChange={handleTableChange}
          loading={loading}
        />
      </Card>
    </Space>
  );
};

export default UserManage; 